package edu.cityu.cs.hk.datastructures;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
 * A simple iterator class for lists. The positions of a list are
 * returned by this iterator. No copy of the list is made, so any
 * changes to the list are reflected in the iterator.
 * @author Michael Goodrich, Eric Zamore
 */
//begin#fragment Iterator
public class PositionIterator implements Iterator { 
  protected List list; // the underlying list
  protected Position cur; // the current (next) position
  public PositionIterator() { } // default constructor
//end#fragment Iterator
  /** Creates an iterator over the given list. */
//begin#fragment Iterator
  public PositionIterator(List L) { // preferred constructor
    list = L;
    if (list.isEmpty()) cur = null;  // list is empty
    else cur = list.first(); // start with the first position
  }
//end#fragment Iterator
  /** Returns whether the iterator has a next object. */
//begin#fragment Iterator
  public boolean hasNext() { return (cur != null); }
//end#fragment Iterator
  /** Returns the next object in the iterator. */
//begin#fragment Iterator
  public Object next() throws NoSuchElementException {
    if (!hasNext()) throw new NoSuchElementException("No next position");
    Position toReturn = cur;
    if (cur == list.last()) cur = null; // no positions left
    else cur = list.next(cur); // move cursor to the next position
    return toReturn;
  }
//end#fragment Iterator
  /** Throws an UnsupportedOperationException in all cases, because
   * removal is not a supported operation in this iterator. */
  public void remove() throws UnsupportedOperationException {
    throw new UnsupportedOperationException("remove");
  }
//begin#fragment Iterator
}
//end#fragment Iterator
